# -*- coding: utf-8 -*-
# File : user_service.py
# Author: taoyahui
# Date : 2021/10/17
from models.user import User
from config import db, admin_address, contract_name, contract_address, contract_abi, redis_service
from results import *
from utils import common_utils
from flask import jsonify


def register_impl(json_dict):
    username = json_dict['username'] # 用户名
    password = json_dict['password'] # 密码
    company_name = json_dict['companyName'] # 公司名称
    company_address = json_dict['companyAddress'] # 账户地址
    role = int(json_dict['companyType']) # 角色 (0管理员 1采购公司 2运输公司)
    location =  json_dict['location']
    bussiness_scope = json_dict['bussinessScope']
    # 判断用户在mysql数据库中是否已经存在
    get_user = User.query.filter_by(username=username).first()
    if get_user is not None:
        return exists_result

    # 调用智能合约中创建用户的功能
    if(role == 1) :
        # 调用智能合约功能，创建“采购公司”
        # 智能合约功能：function createProcureCompany(address companyAddress, string companyName)
        res = common_utils.common_bc_req(admin_address, 
                                         contract_name, 
                                         'createProcureCompany', 
                                         [company_address, company_name], 
                                         contract_address,
                                         contract_abi)
    elif (role == 2) : 
        # 调用智能合约功能，创建“运输公司”
        # 智能合约功能： function createTransCompany(address companyAddress, string companyName, string location, string bussinessScope)

        res = common_utils.common_bc_req(admin_address, 
                                         contract_name, 
                                         'createTransCompany', 
                                         [company_address, company_name, location, bussiness_scope], 
                                         contract_address,
                                         contract_abi)
    else:
        return jsonify(role_type_error)
    
    # 保存数据到Mysql数据库中
    save_user = User(username=username, 
                     password=password, 
                     company_name=company_name,
                     company_address=company_address,
                     role=role, 
                     location=location,
                     bussiness_scope=bussiness_scope)
    db.session.add(save_user)
    db.session.commit()
    return success_result

def login_impl(json):
    username = json['username']
    password = json['password']
    get_user = User.query.filter_by(username=username).first()
    if get_user is None:
        return empty_result
    if get_user.password == password:
        token = common_utils.get_token()
        redis_service.set(token, username)
        data = {
            'token': token,
            'username':username,
            "company_address":get_user.company_address,
            'company_name':get_user.company_name,
            'role': get_user.role,
            'location': get_user.location,
            'bussiness_scope': get_user.bussiness_scope
        }
        return gen_result(200, data)
    else:
        return user_password_error


def get_user_by_token(request):
    username = redis_service.get(request.headers.get('token'))
    if username is None:
        return {
            'code':404001,
            'data':"sername is None"
        }
    get_user = User.query.filter_by(username=username).first()
    if get_user is None:
        return {
            'code':404002,
            'data': 'User not exists'
        }
    else:
        return {
            'code':200,
            'data':get_user
        }

def query_user_info(address):
    # 获取用户信息
    get_user = User.query.filter_by(company_address=address).first()
    
    # 根据用户的权限请求区块链获取相关信息
    # 当role=1 采购公司
    # 当role=2 运输公司
    if get_user.role == 1:
        res = common_utils.common_bc_req(admin_address, 
                                        contract_name, 
                                        'getProcueCompany', 
                                        [address], 
                                        contract_address,
                                        contract_abi)
    elif get_user.role == 2:
        res = common_utils.common_bc_req(admin_address, 
                                        contract_name, 
                                        'getTransCompany', 
                                        [address], 
                                        contract_address,
                                        contract_abi)
    # 解析区块链对应合约中状态变量存储的信息
    res_data = json.loads(res.text)

    result = {
            'username':get_user.username,
            "companyAddress":get_user.company_address,
            'companyName':get_user.company_name,
            'role': get_user.role,
            'location': get_user.location,
            'bussinessScope': get_user.bussiness_scope
    }
    return gen_result(200, result)

def update_user_balance(address, balance):
    """
    修改用户余额功能

    Args:
        address (_type_): _description_
        balance (_type_): _description_

    Returns:
        _type_: _description_
    """
    res = common_utils.common_bc_req(admin_address, 
                                    contract_name, 
                                    'updateUserBalanec', 
                                    [address, balance], 
                                    contract_address,
                                    contract_abi)
    if res.status_code == 200:
        return success_result
    else:
        res_json = json.loads(res.text)
        return gen_result(500, res_json['message'])
    
def submit_transaction(sendAddress, receiveAddress, balance):
    """_summary_
    当前用户(sendAddress)向其他用户(receiveAddress)转账(金额为blance)
    """
    res = common_utils.common_bc_req(sendAddress, 
                                    contract_name, 
                                    'userSubmitTransaction', 
                                    [receiveAddress, balance], 
                                    contract_address,
                                    contract_abi)
    if res.status_code == 200:
        return success_result
    else:
        res_json = json.loads(res.text)
        return gen_result(500, res_json['message'])
    
def query_user_transaction(address):
    """_summary_
    第一步，通过用户地址获取用户关联的交易id
    第二步，通过交易id获取交易的详情
    Args:
        address (_type_): _description_

    Returns:
        _type_: _description_
    """
    # 1. 获取用户相关交易的编号
    res = common_utils.common_bc_req(admin_address, 
                                    contract_name, 
                                    'getUser', 
                                    [address], 
                                    contract_address,
                                    contract_abi)
    res_data = json.loads(res.text)


    # 2. 通过用户交易编号获取交易详情
    tx_list = []
    for i in json.loads(res_data[4]):
        tx_res = common_utils.common_bc_req(admin_address, 
                                    contract_name, 
                                    'getTransaction', 
                                    [i], 
                                    contract_address,
                                    contract_abi)
        tx_data = json.loads(tx_res.text) #拿到了智能合约中getTransaction功能的一个返回数组
        tx_dict = {
            "tid":tx_data[0],
            "sendAddress":tx_data[1],
            "receiveAddress":tx_data[2],
            "status":tx_data[3],
            "balance":tx_data[4]
        }
        tx_list.append(tx_dict)
    result = {
        "send_tx": tx_list,
    }
    return gen_result(200, result)
    

